package com.starblink.home.subscription.child

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toastError
import com.starblink.android.basic.ext.toastWarningL
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.apollo.ext.optionalOrAbsent
import com.starblink.basic.route.RoutePage
import com.starblink.home.subscription.data.SubsCellLoadingModel
import com.starblink.rocketreserver.FetchMerchantWebByIdQuery
import com.starblink.rocketreserver.FetchProductDetailByIdQuery
import com.starblink.rocketreserver.FetchSubscriptionMessageQuery
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.type.SubscriptionMessageReq
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *  Create by yuanl at 2023/10/8
 **/
class SubsChildVM : BaseViewModel() {

    val listDataLD by lazyOnNone {
        MutableLiveData<Boolean>()
    }

    var type: Int? = null

    val list = mutableListOf<Any>().apply {
        add(SubsCellLoadingModel())
        add(SubsCellLoadingModel())
        add(SubsCellLoadingModel())
    }


    var pageNo = 1

    fun requestData(moreData: Boolean = false) {
        viewModelScope.launch {
            if (moreData) {
                pageNo++
            } else {
                pageNo = 1
            }
            SkGqlClient.skQuery(
                FetchSubscriptionMessageQuery(
                    SubscriptionMessageReq(
                        type = type.optional(),
                        pageNo = pageNo.optional(),
                        pageSize = 20.optional(),
                    )
                )
            )?.data?.fetchSubscriptionMessage.let {
                if (pageNo == 1) {
                    list.clear()
                }
                if (it?.isNotEmpty() == true) {
                    list.addAll(it.mapNotNull { it?.subscriptionMessageRespF })
                }
                listDataLD.postValue(it?.isNotEmpty() == true)
            }
        }
    }

    fun routeBrandDiscountState(brandId: String?, discountChange: Boolean?, discount: String?) {
        brandId ?: return
        viewModelScope.launch {
            if (discountChange == true) {
                toastWarningL("The Discount May Have Expired")
                delay(3000L)
            }
            navigationTo(RoutePage.Brand.BRAND_DETAIL){
                extraOf(
                    RoutePage.Brand.ARG_BRAND_ID to brandId,
                    RoutePage.Brand.ARG_IS_DISCOUNT_BRAND to (discount?.isNotEmpty() == true)
                )
            }
        }
    }

    fun routeMerchantDiscountState(merchantNo: String?, discountChange: Boolean?) {
        merchantNo ?: return

        viewModelScope.launch {
            graphQLQuery(FetchMerchantWebByIdQuery(merchantNo))?.data?.fetchMerchantWebById?.merchantWebVOF?.let { it ->
                if (discountChange == true) {
                    toastWarningL("The Discount May Have Expired")
                    delay(2000L)
                    toMerchantWebPage(it)
                } else if (it.productNum > 0) {
                    navigationTo(RoutePage.Store.PAGE_HOME) {
                        extraOf(RoutePage.Store.ID to it.id)
                    }
                } else {
                    toMerchantWebPage(it)
                }
            }
        }
    }

    fun toMerchantWebPage(merchant: MerchantWebVOF) {
        navigationTo(RoutePage.Store.PAGE_LINK) {
            withString(RoutePage.Store.STORE_ID, merchant.id)
            withString(RoutePage.Store.URL, merchant.merchantWebUrl)
            withString(RoutePage.Store.STORE_LOGO, merchant.logo)
            withString(RoutePage.Store.STORE_NAME, merchant.merchantName)
            withBoolean(RoutePage.Store.SUB_OR_NOT, merchant.subOrNot)
        }
    }

    fun routePrdDiscountState(context: Context, prdId: String?, discountChange: Boolean?) {
        prdId ?: return

        if (discountChange == true) {
            toastWarningL("The Discount May Have Expired")
        }
        viewModelScope.launch {
            graphQLQuery(FetchProductDetailByIdQuery(prdId.optionalOrAbsent()))?.data?.fetchProductDetailById?.productF?.let {
                if (discountChange == true) {
                    delay(2000L)
                }
                CommonRoute.startProductLink(
                    context,
                    it.url,
                    it.id.orEmpty(),
                    it.productId.orEmpty(),
                    it.standardSpuIds.orEmpty(),
                    it.collected?:false,
                    it.type,
                    it.merchantWeb?.id?:"",
                    it.merchantWeb?.merchantName?:"",
                    it.merchantWeb?.logo,
                    it.merchantWeb?.subOrNot?:false,
                    it.affInfo?.link,
                    it.traceId.orEmpty(),
                )
            }
        }

    }


}